package com.iwe3.protal.controller;

import com.github.pagehelper.Page;
import com.google.common.hash.BloomFilter;
import com.iwe3.protal.Enum.SystemEnum;
import com.iwe3.protal.aspects.URLIdemAnnotation;
import com.iwe3.protal.common.PageResult;
import com.iwe3.protal.common.R;
import com.iwe3.protal.entity.BookEntity;
import com.iwe3.protal.service.IBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/book")
public class BookController {
    private final IBookService bookServiceImpl;
    private final BloomFilter bloomFilter;

    public BookController(IBookService bookServiceImpl, BloomFilter bloomFilter) {
        this.bookServiceImpl = bookServiceImpl;
        this.bloomFilter = bloomFilter;
    }

    @RequestMapping("/test")
    public R test(@RequestParam("key")String key){
        if(!bloomFilter.mightContain(key)){
            return R.fail(SystemEnum.ILLEGAL);
        }
        System.out.println("正常访问");
        return R.ok();
    }

    @RequestMapping("/loadBookDetailById")
    public R loadBookDetailById(@RequestParam("bookId") Long bookId){

        log.info("loadBookDetailById() 参数为：{}",bookId);

        BookEntity book = bookServiceImpl.getById(bookId);
         return R.ok(book);
    }

    @RequestMapping("/listAllByTypeId")
    public R listAllByTypeId(@RequestParam("typeId") Integer typeId,
                             @RequestParam("currentPage")Integer currentPage,
                             @RequestParam("currentSize")Integer currentSize){
        Page<BookEntity> page = bookServiceImpl.listAllByTypeId(typeId,currentPage,currentSize);
        return R.ok(new PageResult<>(page.getTotal(),page.getResult()));
    }

    @URLIdemAnnotation(timeout = 10L, timeUnit= TimeUnit.SECONDS)
//完整路径：book/top10 -> BookController#listToTop10()
    @GetMapping("/top10")
    public R listToTop10(){
        return R.ok(bookServiceImpl.list2Top10());
    }
}
